<?php
// +----------------------------------------------------------------------
// | 07FLYSAAS [基于ThinkPHP5.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2025-2035 http://www.07fly.xyz
// +----------------------------------------------------------------------
// | Professional because of focus  Persevering because of happiness
// +----------------------------------------------------------------------
// | Author: 开发人生 <goodkfrs@qq.com>
// +----------------------------------------------------------------------

namespace app\plat\model;

/**
 * 授权模型
 */
class TenRoleMenu extends PlatBase
{
    // 获得租户菜单列表
    public function getTenTenantMenu($tenTenantId = 0)
    {
        if (empty($tenTenantId)) {
            $tenTenantId = TEN_TENANT_ID;
        }
        $where['id'] = $tenTenantId;
        $this->modelTenTenant->setIgnoreTenantCheck(true);
        $tenantInfo = $this->modelTenTenant->getInfo($where, '*');
        $moduleIds = $this->modelTenTenantTypeModule->getColumn(['ten_tenant_type_id' => $tenantInfo['ten_tenant_type_id']], 'ten_module_id');
        $menuIds = $this->modelTenModuleMenu->getColumn(['ten_module_id' => ['in', $moduleIds]], 'ten_menu_id');
        //根据角色获得菜单列表
        $where3['id'] = ['in', $menuIds];
        $where3['ten_tenant_id'] = ['=', DATA_DISABLE];
        $menuList = $this->modelTenMenu->getList($where3, '*', 'sort asc', false)->toArray();
        return $menuList;
    }

    // 获得租户菜单列表
    public function getTenUserMenu($tenUserId = 0, $tenTenantId = 0)
    {
        if (empty($tenTenantId)) {
            $tenTenantId = TEN_TENANT_ID;
        }
        if (empty($tenUserId)) {
            $tenUserId = TEN_USER_ID;
        }
        // 获得用户角色菜单列表
        //通过=》userRole-》获得角色ids》角色获得菜单ids》菜单列表
        $where4['a.ten_tenant_id'] = $tenTenantId;
        $where4['a.ten_user_id'] = $tenUserId;
        $this->modelTenUserRole->alias('a');
        $this->modelTenUserRole->join = [
            [SYS_DB_PREFIX . 'ten_role_menu b', 'a.ten_role_id = b.ten_role_id'],
            [SYS_DB_PREFIX . 'ten_menu c', 'b.ten_menu_id = c.id'],
        ];
        $userMenuList = $this->modelTenUserRole->getList($where4, 'a.ten_user_id,b.ten_role_id,c.*', 'c.sort asc', false)->toArray();

        //过滤用户的菜单，不存在于租户菜单列表中的菜单
        // 假设 $tenantMenuList 中的每个元素都有一个唯一的 ten_menu_id=id
        $tenantMenuList = $this->getTenTenantMenu($tenTenantId);
        $tenantMenuIds = array_column($tenantMenuList, 'id');
        // 使用 array_filter 过滤 $userMenuList
        $userMenuList = array_filter($userMenuList, function ($userMenu) use ($tenantMenuIds) {
            return in_array($userMenu['id'], $tenantMenuIds);
        });
        $userMenuList = array_values($userMenuList);

        return $userMenuList;
    }
}